package de.tum.beilmeiner.im.client.controller;

import java.util.Date;

import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.user.client.rpc.AsyncCallback;

import de.novanic.eventservice.client.event.Event;
import de.novanic.eventservice.client.event.RemoteEventService;
import de.novanic.eventservice.client.event.RemoteEventServiceFactory;
import de.novanic.eventservice.client.event.domain.Domain;
import de.novanic.eventservice.client.event.domain.DomainFactory;
import de.novanic.eventservice.client.event.listener.RemoteEventListener;
import de.tum.beilmeiner.im.client.InstantChat;
import de.tum.beilmeiner.im.client.MessagingService;
import de.tum.beilmeiner.im.client.MessagingServiceAsync;
import de.tum.beilmeiner.im.client.UserSessionHandler;
import de.tum.beilmeiner.im.client.event.LoginEvent;
import de.tum.beilmeiner.im.client.view.LoginWindow;
import de.tum.beilmeiner.im.shared.model.UUID;

public class LoginWindowController implements ClickHandler, RemoteEventListener {

	private UserSessionHandler userhandler = null;
	private LoginWindow loginWindow = null;
	private InstantChat mainWindow = null;
	final Domain DOMAIN_UUID = DomainFactory.getDomain(UUID.uuid(15));
	
	public LoginWindowController(LoginWindow loginWindow, UserSessionHandler userhandler, InstantChat mainWindow) {
		
		this.userhandler = userhandler;
		this.loginWindow = loginWindow;
		this.mainWindow = mainWindow;
	
		RemoteEventServiceFactory theEventServiceFactory = RemoteEventServiceFactory.getInstance();
		final RemoteEventService theEventService = theEventServiceFactory.getRemoteEventService();
		
		
		
		theEventService.addListener(DOMAIN_UUID, this);
		loginWindow.addLoginButtonListener(this);

		
		
	}

	@Override
	public void onClick(ClickEvent event) {
		
		MessagingServiceAsync messagingService = GWT.create(MessagingService.class);
		messagingService.sendLoginRequest(DOMAIN_UUID, loginWindow.getUserNameTxt().getText(), loginWindow.getPasswordTxt().getText(), new AsyncCallback<Void>() {

			@Override
			public void onFailure(Throwable caught) {
				// TODO Auto-generated method stub
				
			}

			@Override
			public void onSuccess(Void result) {
				// TODO Auto-generated method stub
				
			}
		});
	}

	@Override
	public void apply(Event anEvent) {

		if(anEvent instanceof LoginEvent)
			onMyEvent((LoginEvent)anEvent);

		
	}

	private void onMyEvent(LoginEvent event) {
		System.out.println("received something..");
		if (event.getUserfromSuccessfulAuthentication() != null) {
			System.out.println("login successfull");
			userhandler.setLoginUser(event.getUserfromSuccessfulAuthentication());
			userhandler.setLoginTime(new Date());
			
			mainWindow.switchToMainView();
		} else {
			System.out.println("login failed..");
		}
		
	}


}
